package com.ITXu.reggie.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ITXu.reggie.commom.R;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
	
	//给basePath注入配置中的路径
	@Value("${reggie.path}")
	private String basePath;
	
	@PostMapping("/upload")
	public R<String> upload(MultipartFile file){
		log.info(file.toString());
		//获得原始文件名
		String originFileName = file.getOriginalFilename();
		//获得文件后缀**使用substring打印从.开始的string数据，beginindex用lastIndexOf去到"."
		//另一个思路是用split方法把originFileName分割成两部分放入一个数组，取数组的【1】号值为suffix
		String suffix = originFileName.substring(originFileName.lastIndexOf("."));
		//使用uuid改造文件名**uuid+suffix后缀
		String fileName = UUID.randomUUID().toString() + suffix;
		System.out.println(fileName);
		//创建一个file对象，路径为basePath，如果basePath指向了一个文件夹格式，则创建一个文件夹
		File driFile = new File(basePath);
		//判断basePath路径的文件夹是否存在
		if (!driFile.exists()) {
			driFile.mkdirs();
		}
		try {
			//将tomcat中的file转存成new File对象，其路径为basePath+文件名
			file.transferTo(new File(basePath+fileName));
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.success(fileName);
	}
	
	@GetMapping("/download")
	public void download(String name, HttpServletResponse response) {
		try {
			//创建输入流，导入数据
			FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));
			//创建输出流，规定写入的指向文件**这次的输出流是从response中取得的，所以最终会写回response中
			ServletOutputStream OutputStream = response.getOutputStream();
			//设置响应的数据格式
			response.setContentType("image/jpeg");
			//创建数组，将输入流的数据写入（read）数组，再用输出流将数组输出（write）
			int len = 0;
			byte[] bytes = new byte[1024];
			while ((len = fileInputStream.read(bytes)) != -1) 
			{
				OutputStream.write(bytes, 0, len);
				OutputStream.flush();
			}
			OutputStream.close();
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
